package com.tuling.sentinelnew.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;


@RestController
@Slf4j
public class HelloController {
    private static final String RESOURCE_NAME = "hello";
    private static final String USER_RESOURCE_NAME = "user";
    private static final String DEGRADE_RESOURCE_NAME = "degrade";

    //进行sentinel流控
    @RequestMapping(value = "/hello")
    public String hello() {
        Entry entry = null;
        try {
            // sentinel针对资源进行限制
            entry = SphU.entry(RESOURCE_NAME);
            String str = "hello world";
            log.info("========" + str + "========");
            return str;
        } catch (BlockException e) {
            log.info("block");
            return "被流控了";
        } catch (Exception ex) {
            // 若需要配置降级规则，需要通过这种方式记录业务异常
            Tracer.traceEntry(ex, entry);
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
        return null;
    }

    @PostConstruct
    private static void initFlowRules() {
//        流控规则
        List<FlowRule> rules = new ArrayList<>();
//        流控
        FlowRule rule = new FlowRule();
//        设置受保护的资源
        rule.setResource(RESOURCE_NAME);
//        设置流控规则 qps
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
//        设置受保护的资源阈值
//        Set Limit QPS to 20
        rule.setCount(1);
        rules.add(rule);
        //加载配置好的规则
        FlowRuleManager.loadRules(rules);
    }
}
